import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { resolve } from 'path'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())

  return {
    base: './', // 配置为相对路径，确保Electron中正确加载资源
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver()]
      })
    ],
    build: {
      outDir: 'dist', // 输出目录
      chunkSizeWarningLimit: 1500, // 增加chunk大小警告限制
      rollupOptions: {
        external: ['electron', 'electron-store', '@electron-toolkit/utils'], // 排除Electron相关依赖
        output: {
          format: 'cjs',
          exports: 'named',
          assetFileNames: (assetInfo) => {
            // 对于图片资源，不添加哈希值
            if (assetInfo.name?.endsWith('.png')) {
              return 'assets/[name][extname]';
            }
            return 'assets/[name]-[hash][extname]';
          }
        }
      },
      emptyOutDir: true // 每次构建前清空输出目录
    },
    optimizeDeps: {
      exclude: ['better-sqlite3'] // 排除sqlite
    },
    server: {
      port: 3000, // 开发服务器端口
      open: false, // 不自动打开浏览器
      strictPort: true, // 严格使用指定端口，不自动切换
      cors: true // 允许跨域请求
    },
    // 定义环境变量
    define: {
      'process.env': {
        ELECTRON_RENDERER_URL: `http://localhost:${env.VITE_PORT || 3000}`,
        NODE_ENV: mode
      }
    },
    // 配置静态资源路径
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    }
  }
})
